package com.lanyou.cook.entity.domain;

import java.util.Arrays;

import javax.persistence.PostLoad;
import javax.persistence.PostPersist;
import javax.persistence.PostRemove;
import javax.persistence.PostUpdate;

import org.apache.commons.lang3.SerializationUtils;

import com.lanyou.cook.service.ApplicationContextKeeper;
import com.lanyou.cook.service.InterfaceScheduleService;

public class InterfaceScheduleEntityListener {
	
	@PostLoad
    private void postLoad(InterfaceSchedule target){
		target.original = (SerializationUtils.clone(target));
    }
	
	@PostPersist
	public void postPersist(InterfaceSchedule target) throws Exception {
		InterfaceScheduleService interfaceScheduleService = ApplicationContextKeeper.getApplicationContext()
				.getBean(InterfaceScheduleService.class);
		interfaceScheduleService.notifyChanged(target.getId());
	}
	
	@PostUpdate
	public void postUpdate(InterfaceSchedule target) throws Exception {
		InterfaceSchedule original = target.original;
		// 运行状态、运行周期单位、运行周期、开始时间、结束调度，其中有一个改变了，都要重新调度
		if (!Arrays.equals(
				new Object[] { original.getRunStatus(), original.getRunWay(), original.getRunCyc(),
						original.getBeginTime(), original.getEndTime() },
				new Object[] { target.getRunStatus(), target.getRunWay(), target.getRunCyc(), target.getBeginTime(),
						target.getEndTime() })) {
			InterfaceScheduleService interfaceScheduleService = ApplicationContextKeeper.getApplicationContext()
					.getBean(InterfaceScheduleService.class);
			interfaceScheduleService.notifyChanged(target.getId());
		}
	}
	
	@PostRemove
	public void postRemove(InterfaceSchedule target) throws Exception {
		InterfaceScheduleService interfaceScheduleService = ApplicationContextKeeper.getApplicationContext()
				.getBean(InterfaceScheduleService.class);
		interfaceScheduleService.notifyChanged(target.getId());
	}
}
